'''
Created on Mar 24, 2013

@author: Petko
'''
from django.views.generic.base import View
from sent.utils import CommonResult, ErrorIds, createValidToken
from sent.utils.result_printer import getPrinter
from sent.model.UserDBManager import UserDBManager

class GetUserGroups(View):
    '''
    classdocs
    '''


    def __init__(self):
        '''
        Constructor
        '''
    
    def get(self, *args, **kwargs):
        accessTokenStr = self.request.GET.get('access_token', None)
        user_id = self.request.GET.get('user_id', None)
        
        cResult = CommonResult()
        try:
            offset = int(self.request.GET.get('offset', 0))
            size = int(self.request.GET.get('size', 50))
        except ValueError:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = 'Bad format'
            return getPrinter().printResult(cResult)
        
        
        if accessTokenStr and user_id:
                
            accessToken, error = createValidToken(accessTokenStr)
            
            if accessToken:
                if (accessToken.owner_ext_id == user_id and accessToken.containsScope('udat')) or accessToken.containsScope('udat_adm'):
                
                    dbMan = UserDBManager(True)
                    try:
                        groups, totalCount = dbMan.getUserGroups(user_id, offset, size)
                        cResult.totalResults = totalCount
                        cResult.errorId = ErrorIds.SUCCESS
                        cResult.result = [group.toPrimitiveDict() for group in groups]
                    finally:
                        dbMan.closeSession()
                else:
                    cResult.errorId = ErrorIds.UNAUTHORIZED
                    cResult.result = "No permission to get groups of %s" % user_id
            else:
                cResult.errorId = ErrorIds.UNAUTHORIZED
                cResult.result = error
        else:
            cResult.errorId = ErrorIds.BADREQUEST
            cResult.result = "Missing parameter"
            
        return getPrinter().printResult(cResult) 